// https://www.lintcode.com/problem/binary-tree-level-order-traversal-ii/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: A tree
     * @return: buttom-up level order a list of lists of integer
     */
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        // write your code here
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        List<TreeNode> nodes = new ArrayList<>();
        nodes.add(root);
        while (nodes.size() > 0) {
            List<Integer> level = new ArrayList<>();
            List<TreeNode> nnodes = new ArrayList<>();
            for (int i = 0; i < nodes.size(); ++i) {
                TreeNode t = nodes.get(i);
                if (t.left != null) {
                    nnodes.add(t.left);
                }
                if (t.right != null) {
                    nnodes.add(t.right);
                }
                level.add(t.val);
            }
            ret.add(level);
            nodes = nnodes;
        }
        Collections.reverse(ret);
        return ret;
    }
}